﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Drawing;
using System.IO;
using UploaderModels;
using UploaderWebApi.Models;

namespace UploaderWebApi.Controllers
{
    public static class ControllerHelper
    {
    
        public static Bitmap ResizeBitmap(Image srcbmp, int width, int height)
        {
            var newimage = new Bitmap(width, height);
            using (var g = Graphics.FromImage(newimage))
            {
                g.DrawImage(srcbmp, 0, 0, width, height);
            }
            return newimage;
        }

        public static string ImageToString(Image image)
        {
            var ms = new MemoryStream();
            image.Save(ms, image.RawFormat);
            byte[] array = ms.ToArray();

            return Convert.ToBase64String(array);
        }

        public static Image CreateImageFromByteArray(byte[] imageData)
        {
            Image image;
            using (var inStream = new MemoryStream())
            {
                inStream.Write(imageData, 0, imageData.Length);

                image = Image.FromStream(inStream);
            }

            return image;
        }

        public static byte[] CreateByteArrayFromImage(Image x)
        {
            var imageConverter = new ImageConverter();
            var xByte = (byte[])imageConverter.ConvertTo(x, typeof(byte[]));
            return xByte;
        }

        public static IEnumerable<ReturnedImageModel> CreateImageList(DbSet<ImageModel> imageModels)
        {
            var list = new List<ReturnedImageModel>();
            
            foreach (var imageModel in imageModels)
            {
                var currentImage = new ReturnedImageModel()
                {
                    Id = imageModel.Id,
                    ImageBytes = imageModel.ImageBytes,
                };
                list.Add(currentImage);

            }

            return list;
        }
    }
}